package cn.hfuu;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @author oldliu
 * @since 1.0
 */
public class WordCount {
    //job
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        if (args.length != 2) {
            System.out.println("using two arguments");
            return;
        }
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "wordcount");
        job.setJarByClass(WordCount.class);
        job.setMapperClass(WordMapper.class);
        job.setCombinerClass(WordReducer.class);
        job.setReducerClass(WordReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }

    //第二个参数，按行读入的文本
    //三，四是输出的格式： dog,1
    //monkey 2
    static class WordMapper extends Mapper<Object, Text, Text, IntWritable> {
        static final Text KEY = new Text();
        static final IntWritable V = new IntWritable(1);

//        @Override
//        protected void setup(Mapper<Object, Text, Text, IntWritable>.Context context) throws IOException,
//                InterruptedException {
//            super.setup(context);
//        }

        @Override
        protected void map(Object key, Text value, Mapper<Object, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {
            //>>>context.getInputSplit()

            String ar[] = value.toString().split("(\\s+|\\.|,|!|:|;)");
            for (String s : ar) {
                //Thread.sleep(25);
                KEY.set(s);
                //V.set(1);
                context.write(KEY, V);
            }
        }
    }

    static class WordReducer extends Reducer<Text, IntWritable, Text, IntWritable> {

        @Override
        protected void reduce(Text key, Iterable<IntWritable> values,
                              Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException,
                InterruptedException {
            int sum = 0;
            for (IntWritable i : values) {
                sum += i.get();
                Thread.sleep(25);
            }
            context.write(key, new IntWritable(sum));///int ->IntWritable
        }
    }
}
